﻿@page "/Downloads"
@page "/Downloads/{Type}"

@using BootstrapBlazor.Components
@using Microsoft.Extensions.Configuration

Files:

<pre>
@{
    if (Type== "BlazorHybrid" )
    {
        var BlazorHybrid = Config["BlazorHybridPath"];
        if (!string.IsNullOrEmpty(Config["BlazorHybridPath"]) && Directory.Exists(Config["BlazorHybridPath"]))
        {
            UploadPath = Config["BlazorHybridPath"];
        }
        else
        {
            UploadPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "BlazorHybrid");
        }

    }
    var files = Directory.GetFiles(UploadPath);
    int i = 0;
    foreach (var item in files)
    {
        i++;
<button class="btn btn-link" @onclick="(()=>DownloadBlob.DownloadFileFromStream(item))">@($"{i}.{Path.GetFileName(item)}")</button><br />
        }
    }
</pre>

<p>@Message</p>

<DownloadBlob OnError="@OnError" @ref="DownloadBlob" />

<button class="btn btn-primary" @onclick="(()=>DownloadTest())">Download File From Stream</button>
<br />


@code{

    [NotNull]
    [Inject]
    private IConfiguration? Config { get; set; }

    [Parameter]
    public string? Type { get; set; }

    /// <summary>
    /// 默认路径, Linux会在/root/uploads, win在 C:\Users\[username]\Documents\uploads
    /// </summary>
    [Parameter]
    public string UploadPath { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "uploads");

    string? Message { get; set; }

    [NotNull]
    DownloadBlob? DownloadBlob { get; set; }


    private Task OnError(string message)
    {
        this.Message = message;
        StateHasChanged();
        return Task.CompletedTask;
    }

    private async Task DownloadTest()
    {
        //生成随机文本内存流
        var stream = new MemoryStream(System.Text.Encoding.Default.GetBytes($"Log from blazor {DateTime.Now:F}"));
        var filename = "test.txt";
        await DownloadBlob.DownloadFileFromStream(filename, stream);
    }
}